<template>
  <div class="app_main">
    <div class="button_box">
      <el-button size="mini" type="primary" plain @click="showRepairDialog">
        待维修设备{{ ('(' + repairTotal + ')') }}
      </el-button>
      <el-button size="mini" type="primary" icon="el-icon-circle-plus-outline" @click="addWorkOrder">新建工单</el-button>
    </div>
    <div class="content">
      <el-tabs v-model="orderType" type="card">
        <el-tab-pane :label="'新安装'+(orderCount['1']>0?'('+orderCount['1']+')':'')" name="1">
          <work-order-content-table ref="table1" :table-data="tableData" :type="1" @search="getList"
                                    @check="showCheckDialog" :current-type="orderType"
          />
        </el-tab-pane>
        <el-tab-pane :label="'上刊'+(orderCount['2']>0?'('+orderCount['2']+')':'')" name="2">
          <work-order-content-table ref="table2" :table-data="tableData" :type="2" @search="getList"
                                    @check="showCheckDialog" :current-type="orderType"
          />
        </el-tab-pane>
        <el-tab-pane :label="'下刊'+(orderCount['3']>0?'('+orderCount['3']+')':'')" name="3">
          <work-order-content-table ref="table3" :table-data="tableData" :type="3" @search="getList"
                                    @check="showCheckDialog" :current-type="orderType"
          />
        </el-tab-pane>
        <el-tab-pane :label="'巡检'+(orderCount['4']>0?'('+orderCount['4']+')':'')" name="4">
          <work-order-content-table ref="table4" :table-data="tableData" :type="4" @search="getList"
                                    @check="showCheckDialog" :current-type="orderType"
          />
        </el-tab-pane>
        <el-tab-pane :label="'维修'+(orderCount['5']>0?'('+orderCount['5']+')':'')" name="5">
          <work-order-content-table ref="table5" :table-data="tableData" :type="5" @search="getList"
                                    @check="showCheckDialog" :current-type="orderType"
          ></work-order-content-table>
        </el-tab-pane>
        <el-tab-pane :label="'换画'+(orderCount['7']>0?'('+orderCount['7']+')':'')" name="7">
          <work-order-content-table ref="table7" :table-data="tableData" :type="7" @search="getList"
                                    @check="showCheckDialog" :current-type="orderType"
          />
        </el-tab-pane>
        <el-tab-pane :label="'中间监播'+(orderCount['8']>0?'('+orderCount['8']+')':'')" name="8">
          <work-order-content-table ref="table8" :table-data="tableData" :type="8" @search="getList"
                                    @check="showCheckDialog" :current-type="orderType"
          />
        </el-tab-pane>
      </el-tabs>
    </div>
    <order-check-dialog :show="checkDialogVisible" :order-id="orderId" :order-name="orderName"
                        :order-type-id="orderTypeId" @close="closeCheckDialog"/>
    <el-dialog title="待维修设备列表" width="70%" :visible.sync="workerRepairVisible" center @close="closeReportDialog">
      <div style="text-align: right;margin-bottom: 10px">
        <el-button v-show="!workerRepairLoading" size="mini" @click="exportExcel">导出</el-button>
      </div>
      <el-table v-loading="workerRepairLoading" :data="worker_repair_list" size="mini" border stripe
                :header-row-style="{'color': 'black','font-weight': 'bold'}" @selection-change="handleSelectionChange"
                :max-height="tableMaxHeight"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index" width="50" align="center" label="序号"></el-table-column>
        <el-table-column width="150" align="center" label="提交时间" prop="created_at" show-overflow-tooltip
        ></el-table-column>
        <el-table-column width="100" align="center" label="故障原因" prop="breakdownName" show-overflow-tooltip></el-table-column>
        <el-table-column width="90" align="center" label="行政区划" prop="area" show-overflow-tooltip></el-table-column>
        <el-table-column width="90" align="center" label="设备编号" prop="code" show-overflow-tooltip></el-table-column>
        <el-table-column width="120" align="center" label="媒体类型" prop="media_type_name" show-overflow-tooltip
        ></el-table-column>
        <el-table-column width="100" align="center" label="尺寸" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.size_height + 'CM' + '*' + scope.row.size_width + 'CM' }}
          </template>
        </el-table-column>
        <el-table-column width="100" align="center" label="工单名称" prop="worker_order_name" show-overflow-tooltip
        ></el-table-column>
        <el-table-column width="180" align="center" label="楼盘" prop="building_area_name" show-overflow-tooltip
        ></el-table-column>
        <el-table-column width="100" align="center" label="楼栋" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.building_number ? scope.row.building_number + '号楼' : scope.row.building_number }}</span>
          </template>
        </el-table-column>
        <el-table-column width="100" align="center" label="单元" show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{ scope.row.unit_number ? scope.row.unit_number + '单元' : scope.row.unit_number }}</span>
          </template>
        </el-table-column>
        <el-table-column width="100" align="center" label="楼层" show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{ scope.row.floor ? scope.row.floor + '层' : scope.row.floor }}</span>
          </template>
        </el-table-column>
        <el-table-column width=" 200
        " align="center" label="地址" prop="address" show-overflow-tooltip
        ></el-table-column>
        <el-table-column width="80" align="center" label="安装工" prop="worker_name" show-overflow-tooltip
        ></el-table-column>
        <el-table-column width="70" align="center" label="安装类型" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="scope.row.install_type == 1">新安装</span>
            <span v-if="scope.row.install_type == 2">上刊</span>
            <span v-if="scope.row.install_type == 3">下刊</span>
            <span v-if="scope.row.install_type == 4">巡检</span>
            <span v-if="scope.row.install_type == 5">维修</span>
          </template>
        </el-table-column>
        <el-table-column width="100" align="center" label="备注" prop="remark" show-overflow-tooltip></el-table-column>
        <el-table-column fixed="right" width="80" align="center" label="状态" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-tag v-if="scope.row.flow_status == 4" type="success" size="mini">通过</el-tag>
            <el-tag v-if="scope.row.flow_status == 2" type="danger" size="mini">未通过</el-tag>
            <el-tag v-if="scope.row.flow_status == 3" type="success" size="mini">待审批</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" width="150" align="center" label="操作" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-button size="mini" icon="el-icon-search" @click="look(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="repairSearchParams.page"
        :page-sizes="[50,100, 200,500,1000]"
        :page-size.sync="repairSearchParams.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="repairTotal"
      >
      </el-pagination>

      <table style="display: none" id="data_table">
        <tr>
          <td style="width: 50px">序号</td>
          <td style="width: 100px">提交时间</td>
          <td style="width: 100px">行政区划</td>
          <td style="width: 100px">设备编号</td>
          <td style="width: 200px">媒体类型</td>
          <td style="width: 80px">尺寸</td>
          <td style="width: 200px">楼盘</td>
          <td style="width: 120px">楼栋</td>
          <td style="width: 120px">单元</td>
          <td style="width: 120px">层数</td>
          <td style="width: 200px">地址</td>
          <td style="width: 80px">安装工</td>
          <td style="width: 80px">安装类型</td>
          <td style="width: 100px">备注</td>
          <td style="width: 80px">状态</td>
          <td style="width: 120px">故障原因</td>
          <td style="width: 100px">历史报备次数</td>
        </tr>
        <tr v-for="(row,index) in worker_repair_list" :key="index">

          <td style="width: 50px">{{ index + 1 }}</td>
          <td style="width: 100px">{{ row.created_at }}</td>
          <td style="width: 100px">{{ row.area }}</td>
          <td style="width: 100px">{{ row.code }}</td>
          <td style="width: 200px">{{ row.media_type_name }}</td>
          <td style="width: 80px">{{ row.size_height + 'CM' + '*' + row.size_width + 'CM' }}</td>
          <td style="width: 200px">{{ row.building_area_name }}</td>
          <td style="width: 120px">{{ row.building_number ? row.building_number + '号楼' : row.building_number }}</td>
          <td style="width: 120px">{{ row.unit_number ? row.unit_number + '单元' : row.unit_number }}</td>
          <td style="width: 120px">{{ row.floor ? row.floor + '层' : row.floor }}</td>
          <td style="width: 200px">{{ row.address }}</td>
          <td style="width: 80px">{{ row.worker_name }}</td>
          <td style="width: 80px">
            <span v-if="row.install_type == 1">新安装</span>
            <span v-if="row.install_type == 2">上刊</span>
            <span v-if="row.install_type == 3">下刊</span>
            <span v-if="row.install_type == 4">巡检</span>
            <span v-if="row.install_type == 5">维修</span>
          </td>
          <td style="width: 100px">{{ row.remark }}</td>
          <td style="width: 80px">
            <el-tag v-if="row.flow_status == 4" type="success" size="mini">通过</el-tag>
            <el-tag v-if="row.flow_status == 2" type="danger" size="mini">未通过</el-tag>
            <el-tag v-if="row.flow_status == 3" type="success" size="mini">待审批</el-tag>
          </td>
          <td style="width: 120px">{{ row.breakdownName }}</td>
          <td style="width: 100px">{{ row.count }}</td>
        </tr>
      </table>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="showCuFormDialog">转维修工单</el-button>
        <el-button size="mini" @click="workerRepairVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
    <el-dialog title="查看" center width="50%" top="100px" :visible.sync="deviceDetailsVisible" append-to-body
               @close="deviceDetail = {}"
    >
      <el-form label-width="120px" label-position="right">
        <el-row :gutter="20">
          <el-col :span="18">
            <el-form-item v-if="deviceDetail != null" label="图片预览">
              <el-carousel :autoplay="false" type="card" height="200px">
                <el-carousel-item v-for="item in deviceDetail.imgList" :key="item">
                  <el-image :src="item" style="height: 200px;width: auto"></el-image>
                </el-carousel-item>
              </el-carousel>
              <el-image style="height:80px;width: 80px;margin: 10px;padding: 5px;border: 1px solid black"
                        v-for="(item,index) in deviceDetail.imgList" :key="index" :src="item"
                        :preview-src-list="deviceDetail.imgList"
              ></el-image>
            </el-form-item>
            <el-form-item label="安装工">
              {{ deviceDetail.worker_name }}
            </el-form-item>
            <el-form-item label="安装类型">
              <span v-if="deviceDetail.install_type == 1">新安装</span>
              <span v-if="deviceDetail.install_type == 2">上刊</span>
              <span v-if="deviceDetail.install_type == 3">下刊</span>
              <span v-if="deviceDetail.install_type == 4">巡检</span>
              <span v-if="deviceDetail.install_type == 5">维修</span>
            </el-form-item>
            <el-form-item label="提交时间">
              {{ deviceDetail.created_at }}
            </el-form-item>
            <el-form-item label="备注">
              {{ deviceDetail.remark }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="工单">
              {{ deviceDetail.work_order_name }}
            </el-form-item>
            <el-form-item label="楼盘">
              {{ deviceDetail.building_area_name }}
            </el-form-item>
            <el-form-item label="媒体类型">
              {{ deviceDetail.media_type_name }}
            </el-form-item>
            <el-form-item v-show="deviceDetail.media_type_id==1" label="楼号">
              {{ deviceDetail.building_number + '号楼' }}
            </el-form-item>
            <el-form-item v-show="deviceDetail.media_type_id==1" label="单元号">
              {{ deviceDetail.unit_number + '单元' }}
            </el-form-item>
            <el-form-item v-show="deviceDetail.media_type_id==1" label="楼层">
              {{ deviceDetail.floor + '层' }}
            </el-form-item>
            <el-form-item v-show="deviceDetail.media_type_id==1" label="楼栋类型">
              {{ deviceDetail.building_type == 1 ? '多层' : '高层' }}
            </el-form-item>
            <el-form-item v-show="deviceDetail.media_type_id==9" label="门号">
              {{ deviceDetail.door_number + '号门' }}
            </el-form-item>
            <el-form-item v-show="deviceDetail.media_type_id==9" label="AB面">
              {{ deviceDetail.ab_type_id == 57 ? 'A面' : 'B面' }}
            </el-form-item>
            <el-form-item v-show="deviceDetail.media_type_id==9" label="是否亮灯">
              {{ deviceDetail.is_light == 0 ? '不亮' : '亮灯' }}
            </el-form-item>
            <el-form-item label="媒体编号">
              {{ deviceDetail.code }}
            </el-form-item>
          </el-col>
        </el-row>
        <div style="text-align: center;margin: 10px 0">当前设备已被工人标记为<span style="color: #e54d42">“存在故障”</span></div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deviceDetailsVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
    <building-tree :show="assignWorkersDialogVisible" :tree-data="treeData" @close="closeAssignWorkersDialog"
                   @save="saveAssignWorkers"
    ></building-tree>
    <el-dialog title="生成维修工单" center width="40%" top="100px" :visible.sync="cuFormDialogVisible" append-to-body
               @close="closeCuFormDialog"
    >
      <el-form ref="cuForm" :model="cuForm" label-width="120px" label-position="right" :rules="rule">
        <el-form-item label="名称" prop="name">
          <el-input v-model="cuForm.name" placeholder="请输入名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="截止时间" prop="deadline">
          <el-date-picker
            v-model="cuForm.deadline"
            type="datetime"
            placeholder="选择工单截止时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="cuForm.remark" type="textarea" placeholder="请输入备注" clearable></el-input>
        </el-form-item>
        <el-form-item label="分配工人">
          <el-button size="mini" type="primary" @click="showWorkerTree">分配工人</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cuFormDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="createWorkOrder">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import workOrderContentTable from './components/workOrderContentTable'
import orderCheckDialog from './components/orderCheckDialog'
import buildingTree from './components/buildingTree'
import {
  getWorkRepairOrderList,
  getWorkerRepairTotal,
  list,
  listBuildingMacthWorker,
  listWorkOrderNumOfType, submit
} from '@/api/workOrder/workOrder'
import { formatDateByFmt, generateUUID } from '@/utils/util'
import XLSX from 'xlsx'

export default {
  name: 'List',
  components: {
    workOrderContentTable,
    orderCheckDialog,
    buildingTree
  },
  data() {
    return {
      tableMaxHeight: 0,
      repairSearchParams:{
        page: 1,
        page_size: 100
      },
      repairListParams:{
        page: 1,
        page_size: 100
      },
      repairTotal: 0,
      orderType: '1',
      orderCount: {
        1: '',
        2: '',
        3: '',
        4: '',
        5: '',
        7: '',
        8: ''
      },
      tableData: [],
      checkDialogVisible: false,
      orderName: '',
      orderId: 0,
      orderTypeId: 0,
      worker_repair_list: [],
      workerRepairVisible: false,
      workerRepairLoading: false,
      deviceDetailsVisible: false,
      deviceDetail: {},
      selectRow: [],
      assignWorkersDialogVisible: false,
      treeData: [],
      selectBuildingIdList: [],
      cuForm: {
        name: null,
        work_order_type_id: 5,
        deadline: null,
        remark: null,
        repairDetailList: [],
        workerSubmitIdList: []
      },
      cuFormDialogVisible: false,
      rule: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        deadline: [{
          required: true, message: '请选择工单截止时间', trigger: 'blur'
        }]
      },
      buildingTreeData: []
    }
  },
  watch: {
    orderType: {
      handler(val, oldVal) {
        this.$refs['table' + val].search()
        this.getOrderTypeCount()
        this.$refs['table' + oldVal].resetListParams()
        this.$refs['table' + val].getAllWorkOrderProgress()
      }
    }
  },
  created() {
    this.tableMaxHeight = (document.documentElement.clientHeight || document.body.clientHeight) - 210
  },
  mounted() {
    this.getOrderTypeCount()
    //this.getWorkRepairOrderList()
    this.$refs['table1'].search()
    this.$refs['table1'].getAllWorkOrderProgress()
    this.getWorkerRepairTotal();
  },
  methods: {
    handleSizeChange(val) {
      this.repairListParams.page_size = val
      this.getWorkRepairOrderList()
    },
    handleCurrentChange(val) {
      this.repairListParams.page = val
      this.getWorkRepairOrderList()
    },
    exportExcel() {
      var table_elt = document.getElementById('data_table')
      var workbook = XLSX.utils.table_to_book(table_elt)
      var ws = workbook.Sheets['Sheet1']
      XLSX.utils.sheet_add_aoa(ws, [])
      XLSX.writeFile(workbook, '待维修维修点位' + (formatDateByFmt(new Date(), 'yyyyMMddhhmmss') + Math.floor(Math.random() * (1000000 - 1) + 1)) + '.xlsx')
    },
    getList(listParams, changeParams) {
      this.tableData = []
      changeParams.tableLoading = true
      list(listParams).then(res => {
        changeParams.tableLoading = false
        this.tableData = res.data.records
        this.tableData.forEach(item => {
          this.$set(item, 'reportGenerateing', false)
          this.$set(item, 'imgPackageGenerateing', false)
        })
        changeParams.total = res.data.total
      })
    },
    addWorkOrder() {
      this.$router.push({
        name: 'install_order_add_page',
        params: {
          is_created: true
        }
      })
    },
    getOrderTypeCount() {
      listWorkOrderNumOfType().then(res => {
        this.orderCount = res.data
      })
    },
    showCheckDialog(id, name, type) {
      this.orderTypeId = type
      this.orderId = id
      this.orderName = name
      this.checkDialogVisible = true
    },
    closeCheckDialog() {
      this.checkDialogVisible = false
      this.$refs['table' + this.orderTypeId].search()
    },
    getWorkRepairOrderList() {
      this.workerRepairLoading = true
      getWorkRepairOrderList(this.repairListParams).then(res => {
        this.workerRepairLoading = false
        this.worker_repair_list = res.data.records
        this.repairTotal = res.data.total
      })
    },
    getWorkerRepairTotal(){
      getWorkerRepairTotal(this.repairListParams).then(res => {
        this.repairTotal = res.data
      });
    },
    showRepairDialog() {
      this.workerRepairVisible = true
      this.getWorkRepairOrderList()
    },
    closeReportDialog() {
      this.selectRow = []
      this.buildingTreeData = []
    },
    look(row) {
      this.deviceDetailsVisible = true
      this.deviceDetail = row
    },
    showWorkerTree() {
      if (this.selectRow.length == 0) {
        this.$message.error('请先选择需要转维修工单的设备记录！')
      } else {
        this.treeData = []
        this.selectBuildingIdList = []
        let buildingWorkers = this.buildingTreeData
        this.selectRow.forEach(item => {
          if (this.selectBuildingIdList.find(building => building == item.building_area_id) === undefined) {
            this.selectBuildingIdList.push(item.building_area_id)
          }
        })
        let data = {
          id: -1,
          label: '常州市',
          children: [],
          is_leaf: false,
          disabled: false
        }
        const loading = this.$loading({
          lock: true,
          text: '加载中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        listBuildingMacthWorker(this.selectBuildingIdList).then(res => {
          res.data.forEach(item => {
            let children = []
            item.buildingAreaList.forEach(building => {
              let find = buildingWorkers.find(item => item.id == building.id)
              if (find) {
                children.push({
                    id: building.id,
                    label: building.name,
                    is_leaf: true,
                    children: [],
                    works: find.works,
                    disabled: false
                  }
                )
              } else {
                children.push({
                    id: building.id,
                    label: building.name,
                    is_leaf: true,
                    children: [],
                    works: [],
                    disabled: false
                  }
                )
              }
            })
            data.children.push({
              id: generateUUID(),
              label: item.area,
              children,
              is_leaf: false,
              disabled: false
            })
          })
          this.treeData.push(data)
          this.assignWorkersDialogVisible = true
          loading.close()
        }).catch(() => {
          loading.close()
        })
      }
    },
    handleSelectionChange(val) {
      this.selectRow = val
      this.cuForm.workerSubmitIdList = this.selectRow.map(item => {
        return item.id
      })
      this.buildingTreeData = []
      this.selectRow.map(item => {
        let find = this.buildingTreeData.find(building => building.id == item.building_area_id)
        if (find === undefined && item.building_area_id != null) {
          let allocationList = []
          allocationList.push({
            media_point_id: item.media_point_id,
            media_type_id: item.media_type_id
          })
          this.buildingTreeData.push(
            {
              allocationList: allocationList,
              id: item.building_area_id,
              works: []
            }
          )
        } else {
          let media = find.allocationList.find(media => media.media_point_id == item.media_point_id)
          if (media === undefined) {
            find.allocationList.push({
              media_point_id: item.media_point_id,
              media_type_id: item.media_type_id
            })
          }
        }
      })
    },
    closeAssignWorkersDialog() {
      this.assignWorkersDialogVisible = false
    },
    showCuFormDialog() {
      if (this.selectRow.length == 0) {
        this.$message.error('请先选择需要转维修工单的设备记录！')
      } else {
        this.cuFormDialogVisible = true
        this.$nextTick(() => {
          this.$refs.cuForm.clearValidate()
        })
      }
    },
    closeCuFormDialog() {
      this.cuForm = {
        name: null,
        work_order_type_id: 5,
        deadline: null,
        remark: null,
        repairDetailList: []
      }
    },
    createWorkOrder() {
      let flag = false
      this.buildingTreeData.forEach(item => {
        if (item.works.length == 0) {
          flag = true
        }
      })
      if (flag) {
        this.$message.error('请分配工人');
        return
      } else {
        this.$refs.cuForm.validate(validate => {
          if (validate) {
            this.cuForm.repairDetailList = []
            this.buildingTreeData.forEach(item => {
              let tmp = {}
              tmp.building_area_id = item.id
              tmp.worker_id_list = item.works.map(worker => {
                return worker.id
              })
              tmp.allocationList = item.allocationList
              this.cuForm.repairDetailList.push(tmp)
            })
            const loading = this.$loading({
              lock: true,
              text: '加载中',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })
            submit(this.cuForm).then(res => {
              if (res.code == 200) {
                this.$message.success('操作成功')
              }
              this.cuFormDialogVisible = false
              this.workerRepairVisible = false
              this.getWorkRepairOrderList()
              this.$refs['table5'].search()
              loading.close()
            }).catch(() => {
              loading.close()
            })
          }
        })
      }
    },
    saveAssignWorkers(data) {
      data.forEach(buiding => {
        let find = this.buildingTreeData.find(item => item.id == buiding.id)
        if (find !== undefined) {
          find.works = buiding.works.map(i => {
            return Object.assign({}, i)
          })
        }
      })
      this.closeAssignWorkersDialog()
    }
  }
}
</script>

<style lang="scss" scoped>
.app_main {
  padding: 0 20px;
}

.content {
  margin-top: 20px;
}

.button_box {
  position: absolute;
  right: 20px;
  z-index: 2;
}
</style>
